<?php
include('includes/connexion.php');
$adminmanager = new AdminManager($connexion);
$elevemanager = new EleveManager($connexion);
session_start();
include('includes/secu.php');
?>
<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
  <title>Tables Advanced - Target Admin</title>

  <meta charset="utf-8">
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width">

  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,700italic,400,600,700">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Oswald:400,300,700">
  <link rel="stylesheet" href="./css/font-awesome.min.css">
  <link rel="stylesheet" href="./js/libs/css/ui-lightness/jquery-ui-1.9.2.custom.min.css">
  <link rel="stylesheet" href="./css/bootstrap.min.css">

  <!-- Plugin CSS -->
  <link rel="stylesheet" href="./js/plugins/icheck/skins/minimal/blue.css">
  <link rel="stylesheet" href="js/plugins/select2/select2.css">
  <link rel="stylesheet" href="js/plugins/datepicker/datepicker.css">
  <link rel="stylesheet" href="js/plugins/simplecolorpicker/jquery.simplecolorpicker.css">
  <link rel="stylesheet" href="js/plugins/timepicker/bootstrap-timepicker.css">
  <link rel="stylesheet" href="js/plugins/fileupload/bootstrap-fileupload.css">
  <link rel="stylesheet" href="js/plugins/magnific/magnific-popup.css">  
  <!-- App CSS -->
  <link rel="stylesheet" href="./css/target-admin.css">
  <link rel="stylesheet" href="./css/custom.css">


  <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
  <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
  <![endif]-->
</head>
<?php 
	$tabQuestion = array(); // tableau des questions
	$question = new QuestionManager($connexion);// on instancie une question avec la connexion en parametre
	$monExercice = new ExerciceManager($connexion); //  on instancie un exercice pour récupérer le nom de l'exercice
	if(!empty($_GET['idExercice'])){
		$idExo = $_GET['idExercice'];
	}else{
		$idExo = $_POST['idRefExercice'];
	}
	
	$typeExo = ""; // on défini le type d'exo à rien au cas où le switch marche pas
	$montype = $monExercice->get($idExo)->type(); // on regarde le type d'exo
	switch ($montype){
		case "R" :
			$typeExo = "Relations"; // sert pour les test de type d'exercice
			break;
		case "A" :
			$typeExo = "Analogie";
			break;
		case "BB" :
			$typeExo = "BriquesBlocs";
			break;
		case "D" :
			$typeExo = "Dominos";
			break;
		case "IP" :
			$typeExo = "InteretPro";
			break;
		case "Q" :
			$typeExo = "Questionnaire";
			break;
		case "SN" :
			$typeExo = "SerieNum";
			break;
		case "TT" :
			$typeExo = "TxtTrous";
			break;
		case "G" :
			$typeExo = "";
			break;
	}	

	
	$tabQuestion = $question->getByExercice($idExo); // on récupere la liste des exercices dans le tableau
	
	// on update un champ
	if(!empty($_POST['ContenuUpdate'])){
		$mquest = $question->get($_POST["idQuestUpdate"]);
		if($_FILES['upload']['name'] != ""){
			$extensions_valides = array( 'jpg' , 'jpeg' , 'gif' , 'png' );
			$extension_upload = strtolower(substr(strrchr($_FILES['upload']['name'], '.'),1));// juste le type sans le . soit png, jpg....
			$chemin_destination = 'uploadImages/'; // le chemin d'enregistrement    
			//RENAME
			$NewNomImage = uniqid('q_'); // nouveau nom !
			$testValide = false; 
			foreach($extensions_valides as $value){ // on test si l'extension est valide
				if($extension_upload == $value){
					$testValide = true;
				}
			}
			
			if($testValide){
				//UPLOAD
				move_uploaded_file($_FILES['upload']['tmp_name'], $chemin_destination.$NewNomImage.".".$extension_upload);	
				$mquest->setImage($chemin_destination.$NewNomImage.".".$extension_upload);	
			}
		}
		$mquest->setContenu($_POST['ContenuUpdate']);
		$question->update($mquest);
		header('Location:question.php?idExercice='.$idExo);			
	}	
	
	//Si on change l'ordre des question
	if(!empty($_GET['ordre']) && !empty($_GET['id'])){
		$quest = $question->get($_GET['id']);
		
		if ($_GET['ordre']=="up"){
			$question->ordreUp($quest->id());
		} else if($_GET['ordre'] == "down"){
			$question->ordreDown($quest->id());
		}
		header('Location:question.php?idExercice='.$idExo); // on redirige	
	}	
	
	// si les champs del et id existent on supprimer la question
	if(!empty($_GET['del']) && !empty($_GET['id'])){
		$quest = $question->get($_GET['id']);
		if (file_exists($quest->image())){
			unlink($quest->image());
		}				
		$question->delete($quest); // on supprime le test
		$question->ReorganizeOrdre($idExo);
		header('Location:question.php?idExercice='.$idExo); // on redirige
	}  	
	
    // si les champs sont remplis on ajoute à la bdd         	
	if( (!empty($_POST['Question']))||( isset($_FILES['upload']) && !empty($_FILES['upload']['name']))){
		
		if(isset($_FILES['upload']) && !empty($_FILES['upload']['name'])){
			
			$extensions_valides = array( 'jpg' , 'jpeg' , 'gif' , 'png' );
			$extension_upload = strtolower(  substr(  strrchr($_FILES['upload']['name'], '.')  ,1)  );// juste le type sans le . soit png, jpg....
			$chemin_destination = 'uploadImages/'; // le chemin d'enregistrement    
			//RENAME
			$NewNomImage = uniqid('q_'); // nouveau nom !
			$testValide = false; 
			foreach($extensions_valides as $value){ // on test si l'extension est valide
				if($extension_upload == $value){
					$testValide = true;
				}
			}
			
			if($testValide){
				//UPLOAD
				move_uploaded_file($_FILES['upload']['tmp_name'], $chemin_destination.$NewNomImage.".".$extension_upload);	
				$chemin = $chemin_destination.$NewNomImage.".".$extension_upload;	
			}
		}		
		
		$maQuestion = new Question(); // on créé une nouvelle question
		$maQuestion->setIdRefExercice($_POST['idRefExercice']); // on ajoute la référence à l'exercice
		
		if(isset($_FILES['upload']) && !empty($_FILES['upload']['name'])){
			$maQuestion->setImage($chemin); // on ajoute l'image de la question
		}
		else {$maQuestion->setImage("Aucune image"); }// on ajoute l'image de la question
		
			
		if(!empty($_POST['Question'])){
			$maQuestion->setContenu($_POST['Question']); // on ajoute le contenu de la question
		}
		else {$maQuestion->setContenu("NoText"); }// on ajoute le contenu de la question
						
		$question->add($maQuestion); // on ajoute la question à la bdd
		
		
		
		header('Location:question.php?idExercice='.$idExo); // on redirige			
	} ?>
<body>

<?php include('includes/navbar.php'); ?>

<?php include('includes/mainbar.php'); ?>

<div class="container">

  <div class="content">

    <div class="content-container">

      <div class="content-header">
        <h2 class="content-header-title">Questions</h2>
        <a href="gestion.php">Tests</a> / <a href="listexercice.php">Exercices</a> / Questions
      </div> <!-- /.content-header --> 

      <div class="row">

        <div class="col-md-12">

          <div class="portlet">

            <div class="portlet-header">

              <h3>
                <i class="fa fa-table"></i>
                Liste des questions de l'exercice "<?php echo $monExercice->get($idExo)->intitule(); ?>"
              </h3>

            </div> <!-- /.portlet-header -->

            <div class="portlet-content">           

              <div class="table-responsive">
				
                <?php if($typeExo == "TxtTrous"){ ?>
                	Lorsque vous entrez votre texte, mettez une balise <b>[/mot]</b> aux endroits auxquels vous souhaitez mettre un trou.
                <?php } ?>
	  <table class="table table-striped table-bordered table-hover table-highlight table-checkable" 
                data-provide="datatable" 
                data-display-rows="10"
                data-info="true"
                data-search="true"
                data-length-change="true"
                data-paginate="false">
        <thead> 
	    <tr>
          
            <th data-filterable="false" data-sortable="true" data-direction="asc">OPTION</th>
            <th data-filterable="false" data-sortable="true" data-direction="asc">QUESTION</th>
            <?php 
			if($typeExo != "TxtTrous"){ 
			echo'<th data-filterable="false" data-sortable="true" data-direction="asc">IMAGE</th>';
            } ?>
            
         	<th data-filterable="false" data-sortable="true" data-direction="asc">ORDRE</th>
        </tr>
        </thead> 
        <tbody>
        <?php 	
			
	
       	foreach($tabQuestion as $quest){
			
			echo "<tr id='question".$quest->id()."'>";
			echo "<td align='center'>";
			
					?><a data-toggle="modal" href="#ModifQuestion" class="fa fa-gear" id="question<?php echo $quest->id(); ?>"></a> | <a href ='?idExercice=<?php echo $idExo; ?>&del=1&id=<?php echo $quest->id(); ?>' style='color:red;' onclick="return(confirm('Etes-vous sûr de vouloir supprimer cette question ?'));"><span class="fa fa-trash-o"></span></a><?php

			if ($typeExo == "Questionnaire"){
			}
			else{
			echo " | <a href ='reponse".$typeExo.".php?idQuestion=".$quest->id()."'>Ajouter des réponses (".$question->getNbReponse($quest->id()).")</a></td>";
			}

			echo "<td>";
				if($quest->contenu() === "NoText"){
					echo "";
				}else{
					echo $quest->contenu();
					if($typeExo == "TxtTrous"){
						echo "<br/><br/>";
						echo "Le texte comporte (".substr_count ( $quest->contenu(), '[/mot]').") mots à trouver.";
						echo"<br/>";
						$position = new ReponseTxtTrousPositionManager($connexion);
						if($position->getByQuestion($quest->id()) == false){
							echo "<font style='color:red'>Assignation des mots à faire.</font>";
						}
						else {echo "<font style='color:green'>Assignation des mots terminée.</font>";}						
					}

					
				}
			echo "</td>";
			if($typeExo != "TxtTrous"){ 
			echo "<td>";
			
			if (file_exists($quest->image())){
				echo "				 
				<div class='tumbnail'>
                    <div class='thumbnail-view'>
                      <a class='thumbnail-view-hover ui-lightbox' href='".$quest->image()."'>
                      </a>
                      <img src='".$quest->image()."' width='125' alt='Gallery Image' />
                    </div>
                 </div>";	
			}
			else{
				echo $quest->image();
			}
				
			
			echo "</td>";
			}
			echo "<td>";
			echo "<a href ='question.php?id=".$quest->id()."&ordre=up&idExercice=".$idExo."' style='color:blue;'><span class='fa fa-angle-double-up'></span></a> ";
			echo $quest->ordre();
			echo " <a href ='question.php?id=".$quest->id()."&ordre=down&idExercice=".$idExo."' style='color:blue;'><span class='fa fa-angle-double-down'></span></a></td>";
			echo "</tr>";
		}
		?></tbody>
	    <tr>
          
          	<form action="question.php" method="post" enctype="multipart/form-data">
            	  <td align="center"><input type="submit" class="btn btn-success" value="Ajouter une Question"/></td>
                                 
                  <td>
                  <?php
				  	if($typeExo == "TxtTrous"){
						echo "<textarea id='text-input' class='form-control' style='resize:vertical' name='Question'></textarea>";
					}
					else{
						echo "<input type='text' name='Question' />";
					}
					
				  ?>
                  	
                  </td>
                  <?php if($typeExo != "TxtTrous"){ ?>
                  <td><input type="file" name="upload" /></td>
                  <?php } ?>
                  <td></td>
                  <input type="hidden" value ="<?php echo $idExo; ?>" name="idRefExercice"/>
            </form>
          
        </tr>
      </table>
              </div> <!-- /.table-responsive -->

            </div> <!-- /.portlet-content -->

          </div> <!-- /.portlet -->

        </div> <!-- /.col -->

      </div> <!-- /.row -->

    </div> <!-- /.content-container -->
      
  </div> <!-- /.content -->

</div> <!-- /.container -->


<?php include('includes/footer.php'); ?>

  <script src="./js/libs/jquery-1.10.1.min.js"></script>
  <script src="./js/libs/jquery-ui-1.9.2.custom.min.js"></script>
  <script src="./js/libs/bootstrap.min.js"></script>

  <!--[if lt IE 9]>
  <script src="./js/libs/excanvas.compiled.js"></script>
  <![endif]-->
  
  <!-- Plugin JS -->
  <script src="./js/plugins/datatables/jquery.dataTables.min.js"></script>
  <script src="./js/plugins/datatables/DT_bootstrap.js"></script>
  <script src="./js/plugins/tableCheckable/jquery.tableCheckable.js"></script>
  <script src="./js/plugins/icheck/jquery.icheck.min.js"></script>
  <script src="js/plugins/magnific/jquery.magnific-popup.min.js"></script>
  <!-- App JS -->
  <script src="./js/target-admin.js"></script>
  
<div id="ModifQuestion" class="modal modal-styled fade">
  <div class="modal-dialog">
    <div class="modal-content">
    <form action="question.php?idExercice=<?php echo $idExo; ?>" id="mformquestion" method="post" class="form parsley-form" enctype="multipart/form-data">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h3 class="modal-title">Modification de l'exercice</h3>
      </div>
      <div class="modal-body">
      	<div class="row">
              <div class="col-md-12">
              <label for="ContenuUpdate">Contenu</label><input type="text" name="ContenuUpdate" />
              </div>
      	</div>
        <hr>
        <div class="row">
        	<div class="col-mid-12">
              <input type="file" name="upload" />
        	</div>
        </div>
      </div>
      <div class="modal-footer">
      	<input type="text" name="idQuestUpdate" hidden/>
        <button type="button" class="btn btn-tertiary" data-dismiss="modal">Fermer</button>
        <input type="submit" class="btn btn-primary" name="mformquestion" value="Sauvegarder"/>
      </div>
      </form>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<script type="text/javascript">
$(document).ready(function() {
	$("a[id^='question']").click(function() {
		
		var id = $(this).attr("id").split("question");

		var test3 = '#question'+id[1]+' td+td';
		
		$("#mformquestion input[name=idQuestUpdate]").val(id[1]);		
				
		$("#mformquestion input[name=ContenuUpdate]").val($(test3).html());
	});
});
</script>
  
</body>
</html>